package com.network.utils.demo.model;

import com.network.utils.demo.http.BaseResponseBean;
import com.network.utils.demo.http.IResultData;
import com.network.utils.demo.http.ResultDataUtil;
import com.network.retrofit.net.ApiResponse;
import com.network.retrofit.net.http.ResponseThrowable;
import com.trello.rxlifecycle3.LifecycleTransformer;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * 项目: com.network.utils.demo
 * 创建人: LuoFG
 * 创建时间: 2021/6/30  15:18
 * 描述:
 */
public abstract class BaseModel<T> extends ApiResponse<BaseResponseBean> implements IResultData<T> {

    @Override
    public void responseData(BaseResponseBean data) {
        ResultDataUtil.getBaseResponseBean(data, getType(), this);
    }

    @Override
    public void responseNull() {

    }

    @Override
    public void netError(ResponseThrowable errorInfo) {
          this.failure(errorInfo.getCode(),errorInfo.getMessage());
    }

    /**
     * 获取解析类型
     *
     * @return
     */
    public Type getType() {
        ParameterizedType genType = (ParameterizedType) getClass().getGenericSuperclass();
        Type[] actualTypeArguments = genType.getActualTypeArguments();
        return actualTypeArguments[0];
    }

    /**
     * @param <UD>
     * @return
     */
    public  <UD> ObservableTransformer<UD,UD> rxConfig(LifecycleTransformer lifecycleTransformer){

        return  new ObservableTransformer<UD, UD>() {
            @Override
            public ObservableSource<UD> apply(Observable<UD> upstream) {
                return   lifecycleTransformer==null?
                        upstream.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                        :   upstream.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).compose(lifecycleTransformer);
            }
        };
    }
}
